const express = require('express');
const router = express.Router();
const Photo = require('../model/Photo');
const uploadFile = require('../middleware/multer');
const fileTools = require('../tools/fsTools');

/* 获取全部相册 */
router.post('/photo.getAll', async (req, res, next) => {
    const photoList = await Photo.getAllPhoto();
    if (photoList) {
        res.send({msg: 's', photoList: photoList});
    } else {
        res.send({msg: 'f'});
    }
});

router.post('/photo.del', async (req, res, next) => {

    const {id, p_img} = req.body;
    const statue = await Photo.delPhoto(id);
    if (statue) {
        fileTools.delFile(p_img);
        res.send({msg: 's'});
    } else {
        res.send({msg: 'f'});
    }


});


//使用uploadFile中间件
router.post("/photo.up", uploadFile, async (req, res, next) => {


    const row = JSON.parse(req.body.row);
    const photo = req.body.photo;
    let p_img = row.p_img;
    if (photo || photo !== "") {
        fileTools.delFile(p_img);
        p_img = '/upload' + req.baseUrl + '/' + req.body.photo;
    }

    const statue = await Photo.upPhoto(p_img, row.id);

    console.log('statue---------------->>' + JSON.stringify(statue));
    res.send({msg: "文件上传成功"});
})


router.post("/photo.add", uploadFile, async (req, res) => {
    const row = JSON.parse(req.body.row);

    const photo = req.body.photo;
    let p_img = '/images/img-1.jpg';
    if (photo || photo !== "") {
        p_img = '/upload' + req.baseUrl + '/' + req.body.photo;
    }
    const statue = await Photo.inPhoto(p_img);
    console.log('statue---------------->>' + JSON.stringify(statue));
    res.send({msg: "文件上传成功"});
})


module.exports = router;
